//
//  KDSegmentPager.m
//  DCTCustomer
//
//  Created by 姚宗超 on 14-9-23.
//  Copyright (c) 2014年 姚宗超. All rights reserved.
//

#import "KDSegmentPager.h"
#import "KDSegmentPagerDelegate.h"
#import "Masonry.h"
#import "UIView+Common.h"

@interface KDSegmentPager ()

@end

@implementation KDSegmentPager

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.pageControl];
    [self.view addSubview:self.contentContainer];
    [self addChildViewController:self.pageViewController];
    [self.contentContainer addSubview:self.pageViewController.view];
    [self setupConstraints];
    [self.pageControl addBottomSeparatorWithLineWidth:0.5f color:[UIColor colorWithHexString:kCellBorderColor] padding:0.0f];
    @weakify(self);
    [self.pageControl setIndexBtnPressedBlock:^(NSInteger index, BOOL isDesc) {
        @normalize(self);
        UIViewController* vc = self.pages[index];
        if ([vc conformsToProtocol:@protocol(KDSegmentPagerDelegate)] && [vc respondsToSelector:@selector(segmentBtnDidPressed:)]) {
            [((UIViewController<KDSegmentPagerDelegate> *)vc) segmentBtnDidPressed:isDesc];
        }
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([self.pages count]>0) {
        [self.pageViewController setViewControllers:@[self.pages[0]]
                                          direction:UIPageViewControllerNavigationDirectionForward
                                           animated:NO
                                         completion:NULL];
    }
    [self updateTitleLabels];
}

- (void)setupConstraints
{
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view);
        make.leading.mas_equalTo(self.view);
        make.trailing.mas_equalTo(self.view);
        make.height.mas_equalTo(@(32.0f));
    }];
    
    [self.contentContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.pageControl.mas_bottom);
        make.left.mas_equalTo(self.view);
        make.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view);
    }];
    
    [self.pageViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(self.contentContainer);
        make.center.mas_equalTo(self.contentContainer);
    }];
}

#pragma mark - property
- (NSMutableArray *)pages
{
    if (!_pages)_pages = [NSMutableArray new];
    return _pages;
}

- (UIPageViewController *)pageViewController
{
    if (!_pageViewController) {
        _pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
        [_pageViewController setDataSource:self];
        [_pageViewController setDelegate:self];
        [_pageViewController.view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
    }
    return _pageViewController;
}

- (HMSegmentedControl *)pageControl
{
    if (!_pageControl) {
        _pageControl = [[HMSegmentedControl alloc] initWithFrame:CGRectZero];
        _pageControl.backgroundColor = [UIColor whiteColor];
        _pageControl.font = [UIFont systemFontOfSize:14.0f];
//        _pageControl.textColor = [UIColor colorWithHexString:kTextBlackColor];
        _pageControl.selectionIndicatorColor = [UIColor colorWithHexString:kHighlightTextColor];
        _pageControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        _pageControl.selectedTextColor = [UIColor colorWithHexString:kHighlightTextColor];
        _pageControl.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe;
        _pageControl.selectionIndicatorHeight = 0.0f;
        [_pageControl addTarget:self
                         action:@selector(pageControlValueChanged:)
               forControlEvents:UIControlEventValueChanged];
    }
    return _pageControl;
}

- (UIView *)contentContainer
{
    if (!_contentContainer) {
        _contentContainer = [[UIView alloc] initWithFrame:CGRectZero];
    }
    return _contentContainer;
}

#pragma mark - Cleanup

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Setup
- (void)updateTitleLabels
{
    [self.pageControl setSectionTitles:[self titleLabels]];
}

- (NSArray *)titleLabels
{
    NSMutableArray *titles = [NSMutableArray new];
    for (UIViewController *vc in self.pages) {
        if ([vc conformsToProtocol:@protocol(KDSegmentPagerDelegate)] && [vc respondsToSelector:@selector(viewControllerTitle)] && [((UIViewController<KDSegmentPagerDelegate> *)vc) viewControllerTitle]) {
            [titles addObject:[((UIViewController<KDSegmentPagerDelegate> *)vc) viewControllerTitle]];
        } else {
            [titles addObject:vc.title ? vc.title : NSLocalizedString(@"NoTitle",@"")];
        }
    }
    return [titles copy];
}

- (void)setPageControlHidden:(BOOL)hidden animated:(BOOL)animated
{
    [UIView animateWithDuration:animated ? 0.25f : 0.f animations:^{
        if (hidden) {
            self.pageControl.alpha = 0.0f;
        } else {
            self.pageControl.alpha = 1.0f;
        }
    }];
    [self.pageControl setHidden:hidden];
    [self.view setNeedsLayout];
}

- (UIViewController *)selectedController
{
    return self.pages[[self.pageControl selectedSegmentIndex]];
}

- (NSUInteger)selectIndex
{
    return [self.pageControl selectedSegmentIndex];
}

- (void)setSelectedPageIndex:(NSUInteger)index animated:(BOOL)animated {
    if (index < [self.pages count]) {
        [self.pageControl setSelectedSegmentIndex:index animated:YES];
        [self.pageViewController setViewControllers:@[self.pages[index]]
                                          direction:UIPageViewControllerNavigationDirectionForward
                                           animated:animated
                                         completion:NULL];
    }
}

#pragma mark - UIPageViewControllerDataSource

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    NSUInteger index = [self.pages indexOfObject:viewController];
    
    if ((index == NSNotFound) || (index == 0)) {
        return nil;
    }
    
    return self.pages[--index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    NSUInteger index = [self.pages indexOfObject:viewController];
    
    if ((index == NSNotFound)||(index+1 >= [self.pages count])) {
        return nil;
    }
    
    return self.pages[++index];
}

- (void)pageViewController:(UIPageViewController *)viewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed
{
    if (!completed){
        return;
    }
    
    [self.pageControl setSelectedSegmentIndex:[self.pages indexOfObject:[viewController.viewControllers lastObject]] animated:YES];
}

#pragma mark - Callback

- (void)pageControlValueChanged:(id)sender
{
    UIPageViewControllerNavigationDirection direction = [self.pageControl selectedSegmentIndex] > [self.pages indexOfObject:[self.pageViewController.viewControllers lastObject]] ? UIPageViewControllerNavigationDirectionForward : UIPageViewControllerNavigationDirectionReverse;
    [self.pageViewController setViewControllers:@[[self selectedController]]
                                      direction:direction
                                       animated:YES
                                     completion:NULL];
}

@end
